package com.redis.sdk.lock;

import com.alibaba.fastjson.JSON;
import com.redis.sdk.RedisClusterUtils;
import com.redis.sdk.cachecore.LockObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class RedisLock implements ILock<LockObject, Object, ProceedingJoinPoint> {

    @Autowired
    private RedisClusterUtils redisClusterUtils;

    @Override
    public Object lock(LockObject lockObject, LockCallBack<ProceedingJoinPoint> lockCallBack) {
        boolean lock = false;
        try {
            log.info("分布式锁参数：{}", JSON.toJSONString(lockObject));
            lock = redisClusterUtils.lock(lockObject);
            log.info("分布式锁结果：{}", lock);
            if (lock) {
                return lockCallBack.callBack();
            } else {
                throw new RuntimeException("系统繁忙！请稍后重试！");
            }
        } catch (Exception e) {
            log.error("执行异常：{}", e.getMessage());
            throw e;
        } finally {
            if (lock) {
                redisClusterUtils.unlock(lockObject);
            }
        }
    }


}
